package com.xinkao.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xinkao.example.dao.RoleDao;
import com.xinkao.example.dao.RoleMenuDao;
import com.xinkao.example.dao.UserDao;
import com.xinkao.example.service.RoleService;
import com.xinkao.example.util.CommonUtil;
import com.xinkao.example.util.constants.Constants;
import com.xinkao.example.util.constants.ErrorEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: ZSX
 * @description: 角色ServiceImpl
 * @date: 2021-01-14 18:20:45
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleDao roleDao;
	@Resource
	RoleMenuDao roleMenuDao;
	@Resource
	private UserDao userDao;

	@Override
	public JSONObject addRole(JSONObject user,JSONObject jsonObject) {
		//登录用户验证
		if (null == user) {
			return CommonUtil.errorJson(ErrorEnum.E_20011);
		}
		//角色名验证
		int exist = roleDao.verifyRole(jsonObject);
		if (exist > 0) {
			return CommonUtil.errorJson(ErrorEnum.E_10009);
		}
		//角色id
		String roleId = UUID.randomUUID().toString().replaceAll("-","");
		jsonObject.put("roleId",roleId);
		jsonObject.put("createBy",user.getString("userName"));
		addPermission(roleId,user.getString("userName"),jsonObject);
		roleDao.addRole(jsonObject);
		return CommonUtil.successJson();
	}

	@Override
	public JSONObject updateRole(JSONObject user,JSONObject jsonObject) {
		//登录用户验证
		if (null == user) {
			return CommonUtil.errorJson(ErrorEnum.E_20011);
		}
		//角色名验证
		String roleName = jsonObject.getString("roleName");
		String roleId =jsonObject.getString("roleId");
		JSONObject oldInfo = roleDao.detailRole(roleId);
		String oldName = oldInfo.getString("roleName");
		if (null != oldInfo && !oldName.equals(roleName)) {
			int exist = roleDao.verifyRole(jsonObject);
			if(exist > 0) {
				return CommonUtil.errorJson(ErrorEnum.E_10009);
			}
		}
		jsonObject.put("createBy",oldInfo.getString("createBy"));
		jsonObject.put("updateBy",user.getString("userName"));
		//删除之前的所有权限
		roleMenuDao.deleteInfoByRoleId(roleId);
		//获取permissionIds(全选中的权限)，和superIds（半选中的权限）遍历加入角色-权限中间表
		addPermission(roleId,user.getString("userName"),jsonObject);
		roleDao.addRole(jsonObject);
		return CommonUtil.successJson();
	}

	public void addPermission(String roleId,String username,JSONObject jsonObject) {
		//获取permissionIds(全选中的权限)，和superIds（半选中的权限）遍历加入角色-权限中间表
		String permissionIds = jsonObject.containsKey("permissionIds") ? StringUtils.strip(jsonObject.getString("permissionIds"),"[]") : null;
		String superIds = jsonObject.containsKey("superIds") ? StringUtils.strip(jsonObject.getString("superIds"),"[]"): null;
		if(StrUtil.isNotEmpty(permissionIds)){
			String[] permissionIdArray = permissionIds.split(",");
			List<JSONObject> roleMenuList = new ArrayList<>();
			for(String menuId : permissionIdArray ) {
				JSONObject info = new JSONObject();
				info.put("roleId",roleId);
				info.put("createBy",username);
				info.put("menuId",menuId.trim());
				info.put("type",Constants.ALL_MENU);
				roleMenuList.add(info);
			}
			roleMenuDao.savePatchInfo(roleMenuList);
		}
		if(StrUtil.isNotEmpty(superIds)){
			String[] superIdArray = superIds.split(",");
			List<JSONObject> roleMenuList = new ArrayList<>();
			for(String menuId : superIdArray ) {
				JSONObject info = new JSONObject();
				info.put("roleId",roleId);
				info.put("createBy",username);
				info.put("menuId",menuId.trim());
				info.put("type",Constants.HALF_MENU);
				roleMenuList.add(info);
			}
			roleMenuDao.savePatchInfo(roleMenuList);
		}
	}

	@Override
	public JSONObject listAllRole(JSONObject jsonObject) {
		CommonUtil.fillPageParam(jsonObject);
		int count = roleDao.countRole(jsonObject);
		List<JSONObject> infoList = roleDao.listAllRole(jsonObject);
		return CommonUtil.successPage(jsonObject, infoList, count);
	}

	@Override
	public JSONObject listRole() {
		List<JSONObject> infoList = roleDao.listRole();
		return CommonUtil.successJson(infoList);
	}

	@Override
	public JSONObject deleteRole(JSONObject jsonObject) {
		String roleId = jsonObject.getString("roleId");
		//判断是否有用户属于此角色
		int exist = userDao.countUserByRole(jsonObject);
		if (exist > 0) {
			return CommonUtil.errorJson(ErrorEnum.E_10011);
		}
		roleDao.deleteRole(roleId);
		return CommonUtil.successJson();
	}

}
